<?php
// send_email.php

// 引入 PHPMailer 类
require __DIR__ . '/PHPMailer/Exception.php';
require __DIR__ . '/PHPMailer/PHPMailer.php';
require __DIR__ . '/PHPMailer/SMTP.php';

// 加载环境变量
function load_env($path)
{
    if (!file_exists($path)) {
        return [];
    }

    $lines = file($path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    $env = [];

    foreach ($lines as $line) {
        if (strpos(trim($line), '#') === 0) {
            continue;
        }
        list($name, $value) = array_map('trim', explode('=', $line, 2));
        $env[$name] = trim($value, '"');
    }

    return $env;
}

$env = load_env(__DIR__ . '/.env');

// 配置日志记录
$log_file = __DIR__ . '/logs/send_email.log';
if (!file_exists(__DIR__ . '/logs')) {
    mkdir(__DIR__ . '/logs', 0777, true);
}

function log_message($level, $message)
{
    global $log_file;
    $date = date('Y-m-d H:i:s');
    $log_entry = "[$date] $level: $message" . PHP_EOL;
    file_put_contents($log_file, $log_entry, FILE_APPEND);
}

// 获取命令行参数
$subject = isset($argv[1]) ? $argv[1] : 'DCO未签署通知';
$body = isset($argv[2]) ? $argv[2] : '你本次提交未签署DCO';
$recipient_email = isset($argv[3]) ? $argv[3] : '';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

// 创建 PHPMailer 实例
$mail = new PHPMailer(true);

try {
    // 服务器设置
    $mail->isSMTP();
    $mail->Host       = isset($env['SMTP_SERVER']) ? $env['SMTP_SERVER'] : 'smtp.example.com';
    $mail->SMTPAuth   = true;
    $mail->Username   = isset($env['SMTP_USERNAME']) ? $env['SMTP_USERNAME'] : 'your_email@example.com';
    $mail->Password   = isset($env['SMTP_PASSWORD']) ? $env['SMTP_PASSWORD'] : 'your_email_password';
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // 或者 PHPMailer::ENCRYPTION_SMTPS
    $mail->Port       = isset($env['SMTP_PORT']) ? $env['SMTP_PORT'] : 587;

    // 收件人
    $mail->setFrom(isset($env['SMTP_USERNAME']) ? $env['SMTP_USERNAME'] : 'your_email@example.com', 'DCO Webhook');
    $mail->addAddress($recipient_email);

    // 内容
    $mail->isHTML(false);
    $mail->Subject = $subject;
    $mail->Body    = $body;

    $mail->send();
    log_message('INFO', "邮件发送成功给 {$recipient_email}，主题: {$subject}");
} catch (Exception $e) {
    log_message('ERROR', "邮件发送失败: {$mail->ErrorInfo}");
}
